package com.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class WebFiter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //判断请求开放
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取当前请求
        String path = request.getServletPath();
        System.out.println("当前请求："+path);
        //允许访问
        if (path.contains("/images") || path.contains("/css") || path.contains("/js") || "/login.jsp".equals(path) || "/UsersServlet".equals(path) || "/register.jsp".equals(path)) {
            System.out.println("yunxufangwen");
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            Object username = request.getSession().getAttribute("user_name");
            if (username != null) {
                //session处于登录情况下开放所有功能
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                System.out.println("请先登录再访问");
                request.setAttribute("err","请先登录再访问");
                request.getRequestDispatcher("register.jsp").forward(request,response);
            }


        }

    }

    @Override
    public void destroy() {

    }
}
